package net.wyy.ssoclient.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Enzo Cotter on 2019/11/21.
 */
@Component
public class TokenLoginInterceptor implements HandlerInterceptor {

    @Value("${sso.server.validateUrl}")
    private String ssoServerUrl;
    @Value("${sso.server.login}")
    private String ssoServerLogin;

    private RestTemplate restTemplate = new RestTemplate();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        String currentLocation = getLocation(request);
        System.out.println("currentLocation: "+currentLocation);
        if(StringUtils.isNotBlank(token)){
            // 验证 sso token
            boolean valid = validate(request,token);
            if(valid){
                // 未登陆,跳转到 sso server
                response.sendRedirect(currentLocation);
                return false;
            }else{
                // 验证失败
                request.getSession().removeAttribute("userId");
            }
        }

        return true;
    }

    private String getLocation(HttpServletRequest request) {
        return request.getScheme()+"://"+request.getHeader("host")+request.getServletPath();
    }

    private boolean validate(HttpServletRequest request, String token) {
        Boolean valid = restTemplate.getForObject(ssoServerUrl+"?token="+token, Boolean.class);
        if(valid){
            request.getSession().setAttribute("userId",token.split("/")[1]);
        }
        return valid;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
